package com.wxx.db;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.mysql.jdbc.Driver;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

public class DBManager {
    public static SqlSessionFactory sqlSessionFactory = null;
    public static MybatisConfiguration configuration = null;

    static {
        sqlSessionFactory = initSqlSessionFactory();
    }

    private static SqlSessionFactory initSqlSessionFactory() {
        SimpleDriverDataSource dataSource = dataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("Production", transactionFactory, dataSource);
        configuration = new MybatisConfiguration(environment);
//        configuration.setLogImpl(StdOutImpl.class);
        return new MybatisSqlSessionFactoryBuilder().build(configuration);
    }

    private static SimpleDriverDataSource dataSource() {
        SimpleDriverDataSource dataSource = null;
        try {
            dataSource = new SimpleDriverDataSource();
            dataSource.setDriverClass(Driver.class);
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/crawler?characterEncoding=utf8&useSSL=false&serverTimezone=UTC");
            dataSource.setUsername("wxx");
            dataSource.setPassword("123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }
}
